<script lang='ts'>
import { defineComponent, ref, reactive, onMounted,onUnmounted } from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from 'element-plus'
import { getVierificationCode, Login } from "@/api/login/index";
import { useStore } from "vuex";
import { log } from "console";

interface FormModule {
  username: string;
  password: string;
  verificationCode: string;
  uuid: string;
}

export default defineComponent({
  name: "Login",
  components: {},
  setup() {
    const store = useStore();
    //label对齐方式
    const labelPosition = "left";
    //路由
    const router = useRouter();
    //表单引用
    const ruleForm: any = ref(null);
    //登录表单数据
    const loginForm = reactive<FormModule>({
      username: "",
      password: "",
      verificationCode: "",
      uuid: "",
    });

    const checkCode = (rule: any, value: string, callback: any) => {
      if (value.length != 4) {
        callback(new Error("请输入四位验证码"));
      }
      callback();
    };

    //验证
    const rules = reactive({
      userName: [{ required: true, message: "请输入账号" }],
      passWord: [{ required: true, message: "请输入密码" }],
      verificationCode: [{ validator: checkCode, required: true }],
    });

   

    const doLogin = () => {
      refreshVCode();
      ruleForm.value?.validate((valid: any) => {
        if (valid) {
          console.log(valid);
          Login(
            loginForm.username,
            loginForm.password,
            loginForm.verificationCode,
            loginForm.uuid
          ).then((res) => {
            if (res.data.state === "error") {
              ElMessage({
                message: res.data.message,
                type: 'error',
              })
            } else {
              store.dispatch('user/CHANGEUSERINFO',res.data.data);
              router.push("/portal");
            }
          });
        } else {
          console.log("validate error!!");
          return false;
        }
      });
    };

    const getImageUrl = (name: string) => {
      return new URL(`/src/assets/images/${name}`, import.meta.url).href;
    };
    //base64  验证码
    const vierificationCodeBase64 = ref<string>();
    //刷新
    const refreshVCode = async () => {
      const result = await getVierificationCode();
      console.log(result);

      vierificationCodeBase64.value =
        "data:" +
        result.data.data.respon_data.ContentType +
        ";base64," +
        result.data.data.respon_data.FileContents;

      loginForm.uuid = result.data.data.uuid;

    };

    onMounted(async () => {
      await refreshVCode();
      
      
      //enter登录
       document.onkeydown = function (e) {
        var key = (window as any).event.keyCode;
        if (key == 13) {
          refreshVCode();
          doLogin();
        }
      };
    });

     onUnmounted(() => {
      document.onkeydown = function (e) {};
    });

    return {
      labelPosition,
      loginForm, //表单输入数据
      ruleForm, //表单标签引用
      doLogin,
      getImageUrl,
      rules,
      vierificationCodeBase64,
      refreshVCode,
    };
  },
});
</script>

<template>
  <div class="login-page-wrap">
    <div class="login-page-title">
      <img :src="getImageUrl('logo.png')" style="width: 60px; height: 60px" />
      巴音郭楞蒙古自治州国土空间基础信息平台
    </div>
    <div class="login-page-content">
      <el-image style="width: 100%; height: 100%" :src="getImageUrl('login_bg.jpeg')" fit="cover"></el-image>
      <el-card class="login-form-wrap box-card">
        <template #header>
          <span class="login--header">登录</span>
        </template>
        <el-form :label-position="labelPosition" :model="loginForm" ref="ruleForm">
          <el-form-item prop="username" :rules="rules.userName">
            <el-input v-model="loginForm.username" placeholder="请输入账号">
              <template #prefix>
                <i class="el-input__icon el-icon-user"></i>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="password" :rules="rules.passWord">
            <el-input v-model="loginForm.password" placeholder="请输入密码" show-password>
              <template #prefix>
                <i class="el-input__icon el-icon-lock"></i>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item prop="verificationCode" :rules="rules.verificationCode">
            <el-col :span="18">
              <el-input
                style="width: 270px"
                v-model="loginForm.verificationCode"
                placeholder="请输入验证码"
              ></el-input>
            </el-col>
            <el-col
              :span="5"
              style="
                display: flex;
                align-items: center;
                height: 40px;
                padding-left: 10px;
              "
            >
              <img :src="vierificationCodeBase64" @click="refreshVCode" />
            </el-col>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" class="login--button" @click="doLogin">登录</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
  </div>
</template>

<style lang='less' scoped>
.login-page-wrap {
  width: 100vw;
  height: 100vh;
  background-color: white;
  user-select: none;

  .login-page-title {
    display: flex;
    justify-content: center;
    height: 2em;
    line-height: 2em;
    font-size: 2em;
    padding: 20px;
    &:before {
      content: "";
      overflow: hidden;
    }
  }
  .login-page-content {
    height: 70%;
    margin: auto 0;
    position: relative;
    .login-form-wrap {
      position: absolute;
      top: 20%;
      right: 10%;
      width: 400px;

      .login--header {
        font-size: 24px;
        font-weight: 600;
      }

      .form--input {
        width: 100%;

        :deep(.el-input__inner) {
          padding-left: 40px;
        }
      }

      .login--button {
        width: 100%;
      }
    }
  }
}
</style>
